/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple.utils.data;

import com.google.common.base.Preconditions;
import com.google.common.io.BaseEncoding;
import simple.utils.cache.ByteArray;

import java.nio.ByteBuffer;
import java.util.UUID;

/**
 * Check validity of GUID
 * when there is  guid with no '-' it creates the same with '-'
 *
 * @author rehak
 */
public class GUIDUtils {

    public static String randomStringGUID() {
        return UUID.randomUUID().toString();
    }

    public static ByteArray randomGUID() {
        UUID uuid = UUID.randomUUID();
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        return ByteArray.wrap(bb.array());
    }

    /**
     * if there are '-' in the guid it deletes them
     *
     * @param guid
     * @return
     */
    public static byte[] toBytes(String guid) {
        Preconditions.checkNotNull(guid);
        guid = guid.trim().replace("-", "");
        return BaseEncoding.base16().lowerCase().decode(guid);
    }

    /**
     * Put '-' to 8,13,18 and 23 position of byte array
     *
     * @param bytes byte array GUID
     * @return
     */
    public static String fromBytes(byte[] bytes) {
        String enc = BaseEncoding.base16().lowerCase().encode(bytes);
        StringBuilder sb = new StringBuilder(enc);
        sb.insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-');
        return sb.toString();
    }

    /**
     * @param guid
     * @return guid in correct form
     */
    public static String clear(String guid) {
        return fromBytes(toBytes(guid));
        //return fromBytes(guid.getBytes());
    }


}
